import {Component, Input, OnInit, Output} from '@angular/core';
import {FileUploader} from 'ng2-file-upload';
import {NbDialogRef} from '@nebular/theme';
import {NativeService} from '../../../services/native.service';
import {StorageService} from '../../../services/storage.service';
import {StorageKey} from '../../../storage.key';

@Component({
  selector: 'ngx-import',
  templateUrl: './import.component.html',
  styleUrls: ['./import.component.scss'],
})
export class ImportComponent implements OnInit {
  flie: any; // 导入用户信息
  selectFileName: any = '未选择文件';
  token: any;
  // 初始化
  public uploader: FileUploader;
  @Input() title: string;
  @Output() address: string;
  constructor(private ref: NbDialogRef<ImportComponent>,
              private nativeService: NativeService,
              private storageService: StorageService) {
  }

  async ngOnInit() {
    this.token = await this.storageService.get(StorageKey.TOKEN);
    console.log(this.token);
    this.uploader = new FileUploader({
      url: this.address, // 上传地址
      method: 'POST', // 上传方式
      itemAlias: 'file',  // 别名（后台接受参数名）
      autoUpload: false,  // 是否自动上传（如果为true，则在input选择完后自动上传）
      headers : [{name: 'token', value: this.token}], // 上传时加消息头(加token值)
    });
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
  }

  selectedFileOnChanged(event: any) {
    // 打印文件选择名称
    this.selectFileName = event.target.value.substr(event.target.value.lastIndexOf('\\') + 1);
    console.log(this.selectFileName);
  }


  async uploadFile() {
    console.log('uploadFile');
    console.log(this.uploader);
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      console.log(this.uploader.queue[0]);
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const res = JSON.parse(response);
        console.log('res', res);
        if (res.data) {
          this.ref.close(res.data);
          this.nativeService.showToast('success', '导入成功');
        } else {
          this.nativeService.showError( res.msg);
        }
      } else {
        // 上传文件后获取服务器返回的数据错误
        console.log('err', response, status, headers);
        console.log('err', Error);
      }
    };
    this.uploader.queue[0].upload(); // 开始上传
    console.log(this.uploader.queue[0]);
  }

  cancel() {
    this.ref.close();
  }

}
